package com.nttdata.ta.user.controller;

import com.nttdata.ta.common.dto.LoginRequest;
import com.nttdata.ta.common.dto.LoginResponse;
import com.nttdata.ta.common.dto.RegisterRequest;
import com.nttdata.ta.common.dto.ResponseResult;
import com.nttdata.ta.common.dto.UserDTO;
import com.nttdata.ta.common.entity.User;
import com.nttdata.ta.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/auth")
public class AuthController {
    
    private final UserService userService;
    
    @PostMapping("/login")
    public ResponseEntity<ResponseResult<LoginResponse>> login(@RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse loginResponse = userService.login(loginRequest);
            return ResponseEntity.ok(ResponseResult.success("登录成功", loginResponse));
        } catch (Exception e) {
            log.error("登录失败", e);
            return ResponseEntity.badRequest().body(ResponseResult.fail(e.getMessage()));
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<ResponseResult<UserDTO>> register(@RequestBody RegisterRequest registerRequest) {
        try {
            User user = userService.register(registerRequest);
            UserDTO userDTO = new UserDTO(
                    user.getId(),
                    user.getUsername(),
                    user.getEmail(),
                    user.getFullName(),
                    user.isEnabled(),
                    user.getRole()
            );
            return ResponseEntity.ok(ResponseResult.success("注册成功", userDTO));
        } catch (Exception e) {
            log.error("注册失败", e);
            return ResponseEntity.badRequest().body(ResponseResult.fail(e.getMessage()));
        }
    }
    
    @PostMapping("/register-admin")
    public ResponseEntity<ResponseResult<UserDTO>> registerAdmin(@RequestBody RegisterRequest registerRequest) {
        try {
            User user = userService.registerAdmin(registerRequest);
            UserDTO userDTO = new UserDTO(
                    user.getId(),
                    user.getUsername(),
                    user.getEmail(),
                    user.getFullName(),
                    user.isEnabled(),
                    user.getRole()
            );
            return ResponseEntity.ok(ResponseResult.success("管理员注册成功", userDTO));
        } catch (Exception e) {
            log.error("管理员注册失败", e);
            return ResponseEntity.badRequest().body(ResponseResult.fail(e.getMessage()));
        }
    }
} 